#!/usr/bin/env bash
set -euo pipefail

# MongoDB deployment script for Longxin (Aliyun Linux) 7.9
# - Installs to /opt/RadMedical/product/tool/mongodb
# - Creates dedicated user/group
# - Writes mongod.conf
# - Registers systemd unit with resource limits:
#   * MemoryMax = 20% of host
#   * CPUQuota = 20% of host CPUs (and also restricts to 2 CPUs max)
# - Enables and starts on boot
#
# Version source (requested RPM):
# https://repo.mongodb.org/yum/redhat/7/mongodb-org/6.0/x86_64/RPMS/mongodb-org-server-6.0.26-1.el7.x86_64.rpm

MONGODB_BASE_DIR="/opt/RadMedical/product/tool/mongodb"
MONGODB_DATA_DIR="${MONGODB_BASE_DIR}/data"
MONGODB_LOG_DIR="${MONGODB_BASE_DIR}/logs"
MONGODB_CONF_DIR="${MONGODB_BASE_DIR}/conf"
MONGODB_BIN_DIR="${MONGODB_BASE_DIR}/bin"
MONGODB_USER="mongod"
MONGODB_GROUP="mongod"
SYSTEMD_UNIT="/etc/systemd/system/mongod.service"

# MongoDB connection credentials
MONGODB_DB_USER="raip"
MONGODB_DB_PASSWORD="hmgsoft"
MONGODB_DB_NAME="raip"
MONGODB_PORT="27017"

# Auto-detect IPv4 address (preferred) or hostname
get_mongodb_host() {
	# Allow override via environment variable
	if [[ -n "${MONGODB_HOST:-}" ]]; then
		echo "${MONGODB_HOST}"
		return
	fi
	
	# Priority 1: Try to get IPv4 address first
	local ip_val
	# Try multiple methods to get IPv4 address (excluding 127.0.0.1)
	# Method 1: ip command
	ip_val="$(ip -4 addr show 2>/dev/null | grep 'inet ' | awk '{print $2}' | cut -d'/' -f1 | grep -v '^127\.' | head -n 1)"
	# Method 2: hostname -I
	if [[ -z "${ip_val}" ]]; then
		ip_val="$(hostname -I 2>/dev/null | awk '{for(i=1;i<=NF;i++){if($i!~/^127\./ && $i~/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/){print $i;exit}}}')"
	fi
	# Method 3: hostname -i
	if [[ -z "${ip_val}" ]]; then
		ip_val="$(hostname -i 2>/dev/null | awk '{for(i=1;i<=NF;i++){if($i!~/^127\./ && $i~/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/){print $i;exit}}}')"
	fi
	# Method 4: ifconfig (fallback)
	if [[ -z "${ip_val}" ]]; then
		ip_val="$(ifconfig 2>/dev/null | grep -E 'inet [0-9]' | awk '{print $2}' | grep -v '^127\.' | head -n 1)"
	fi
	if [[ -n "${ip_val}" ]]; then
		echo "${ip_val}"
		return
	fi
	
	# Priority 2: Fallback to hostname
	local hostname_val
	hostname_val="$(hostname 2>/dev/null || echo '')"
	if [[ -n "${hostname_val}" && "${hostname_val}" != "localhost.localdomain" ]]; then
		echo "${hostname_val}"
		return
	fi
	
	# Last resort: localhost
	echo "localhost"
}

MONGODB_HOST="$(get_mongodb_host)"
MONGODB_CONNECTION_STRING="mongodb://${MONGODB_DB_USER}:${MONGODB_DB_PASSWORD}@${MONGODB_HOST}:${MONGODB_PORT}/${MONGODB_DB_NAME}?authSource=${MONGODB_DB_NAME}&authMechanism=SCRAM-SHA-1"

# Default RPM URL (RHEL7 x86_64)
DEFAULT_RPM_URL="https://repo.mongodb.org/yum/redhat/7/mongodb-org/6.0/x86_64/RPMS/mongodb-org-server-6.0.26-1.el7.x86_64.rpm"
MONGODB_RPM_URL="${MONGODB_RPM_URL:-$DEFAULT_RPM_URL}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Allow specifying a local RPM path explicitly (takes precedence)
MONGODB_RPM_PATH="${MONGODB_RPM_PATH:-}"
# Allow specifying a local mongosh tgz path explicitly (takes precedence)
MONGOSH_TGZ_PATH="${MONGOSH_TGZ_PATH:-}"

ensure_root() {
	if [[ "${EUID}" -ne 0 ]]; then
		echo "请以 root 用户运行此脚本。"
		exit 1
	fi
}

create_user_group() {
	if ! getent group "${MONGODB_GROUP}" >/dev/null 2>&1; then
		groupadd --system "${MONGODB_GROUP}" || {
			echo "错误: 创建用户组 ${MONGODB_GROUP} 失败"
			exit 1
		}
	fi
	if ! id -u "${MONGODB_USER}" >/dev/null 2>&1; then
		useradd --system --no-create-home --shell /sbin/nologin --gid "${MONGODB_GROUP}" "${MONGODB_USER}" || {
			echo "错误: 创建用户 ${MONGODB_USER} 失败"
			exit 1
		}
	fi
	# 验证用户和组确实存在
	if ! id -u "${MONGODB_USER}" >/dev/null 2>&1; then
		echo "错误: 用户 ${MONGODB_USER} 创建后验证失败"
		exit 1
	fi
	if ! getent group "${MONGODB_GROUP}" >/dev/null 2>&1; then
		echo "错误: 用户组 ${MONGODB_GROUP} 创建后验证失败"
		exit 1
	fi
	echo "用户和组创建成功: ${MONGODB_USER}:${MONGODB_GROUP}"
}

prepare_dirs() {
	# Check and create base directory if it doesn't exist
	if [[ ! -d "${MONGODB_BASE_DIR}" ]]; then
		echo "正在创建 MongoDB 基础目录: ${MONGODB_BASE_DIR}"
		mkdir -p "${MONGODB_BASE_DIR}"
	fi
	
	# Create subdirectories
	mkdir -p "${MONGODB_BIN_DIR}" "${MONGODB_DATA_DIR}" "${MONGODB_LOG_DIR}" "${MONGODB_CONF_DIR}"
	
	# Set ownership and permissions (验证用户存在后再设置)
	if id -u "${MONGODB_USER}" >/dev/null 2>&1 && getent group "${MONGODB_GROUP}" >/dev/null 2>&1; then
		chown -R "${MONGODB_USER}:${MONGODB_GROUP}" "${MONGODB_BASE_DIR}" || {
			echo "错误: 设置目录所有者失败"
			exit 1
		}
		chmod 0755 "${MONGODB_BASE_DIR}" "${MONGODB_BIN_DIR}" "${MONGODB_CONF_DIR}"
		chmod 0750 "${MONGODB_DATA_DIR}"
		chmod 0755 "${MONGODB_LOG_DIR}"
	else
		echo "错误: 用户 ${MONGODB_USER} 或组 ${MONGODB_GROUP} 不存在，无法设置目录权限"
		exit 1
	fi
}

install_from_rpm() {
	local tmpdir
	tmpdir="$(mktemp -d)"
	# Cleanup on exit
	cleanup_rpm() {
		[[ -n "${tmpdir:-}" && -d "${tmpdir}" ]] && rm -rf "${tmpdir}" 2>/dev/null || true
	}
	trap cleanup_rpm EXIT

	local rpm_src=""
	# Priority 1: explicit local path via env
	if [[ -n "${MONGODB_RPM_PATH}" && -f "${MONGODB_RPM_PATH}" ]]; then
		rpm_src="${MONGODB_RPM_PATH}"
		echo "使用本地 RPM 文件 (MONGODB_RPM_PATH): ${rpm_src}"
	# Priority 2: same directory as this script (offline install)
	elif [[ -f "${SCRIPT_DIR}/mongodb-org-server-6.0.26-1.el7.x86_64.rpm" ]]; then
		rpm_src="${SCRIPT_DIR}/mongodb-org-server-6.0.26-1.el7.x86_64.rpm"
		echo "使用脚本同目录下的本地 RPM 文件: ${rpm_src}"
	# Priority 3: fallback to download (requires internet)
	else
		echo "未找到本地 RPM 文件，正在尝试下载: ${MONGODB_RPM_URL}"
		curl -fsSL "${MONGODB_RPM_URL}" -o "${tmpdir}/mongodb-org-server.rpm"
		rpm_src="${tmpdir}/mongodb-org-server.rpm"
	fi

	if command -v yum >/dev/null 2>&1; then
		yum -y localinstall "${rpm_src}" || rpm -Uvh --force --nodeps "${rpm_src}"
	else
		rpm -Uvh --force "${rpm_src}"
	fi

	# Optionally copy common tools into our bin dir, if present
	for tool in mongod mongo mongosh bsondump mongotop mongostat mongorestore mongodump; do
		if command -v "${tool}" >/dev/null 2>&1; then
			cp -f "$(command -v "${tool}")" "${MONGODB_BIN_DIR}/" || true
		fi
	done
	# 验证用户存在后再设置权限
	if id -u "${MONGODB_USER}" >/dev/null 2>&1 && getent group "${MONGODB_GROUP}" >/dev/null 2>&1; then
		chown -R "${MONGODB_USER}:${MONGODB_GROUP}" "${MONGODB_BIN_DIR}" 2>/dev/null || true
		chmod 0755 "${MONGODB_BIN_DIR}/"* 2>/dev/null || true
	else
		echo "警告: 用户 ${MONGODB_USER} 或组 ${MONGODB_GROUP} 不存在，跳过权限设置"
	fi
}

install_mongosh() {
	# Check if mongosh is already available
	if command -v mongosh >/dev/null 2>&1 && [[ -f "${MONGODB_BIN_DIR}/mongosh" ]]; then
		echo "mongosh 已安装: ${MONGODB_BIN_DIR}/mongosh"
		return 0
	fi

	local tmpdir
	tmpdir="$(mktemp -d)"
	# Cleanup on exit
	cleanup_mongosh() {
		[[ -n "${tmpdir:-}" && -d "${tmpdir}" ]] && rm -rf "${tmpdir}" 2>/dev/null || true
	}
	trap cleanup_mongosh EXIT

	local tgz_src=""
	# Priority 1: explicit local path via env
	if [[ -n "${MONGOSH_TGZ_PATH}" && -f "${MONGOSH_TGZ_PATH}" ]]; then
		tgz_src="${MONGOSH_TGZ_PATH}"
		echo "使用本地 mongosh tgz 文件 (MONGOSH_TGZ_PATH): ${tgz_src}"
	# Priority 2: same directory as this script (offline install)
	elif [[ -f "${SCRIPT_DIR}/mongosh-2.5.9-linux-x64.tgz" ]]; then
		tgz_src="${SCRIPT_DIR}/mongosh-2.5.9-linux-x64.tgz"
		echo "使用脚本同目录下的本地 mongosh tgz 文件: ${tgz_src}"
	# Priority 3: try to find any mongosh-*.tgz in script directory
	else
		local found_tgz
		found_tgz="$(find "${SCRIPT_DIR}" -maxdepth 1 -name "mongosh-*.tgz" -type f 2>/dev/null | head -n 1)"
		if [[ -n "${found_tgz}" && -f "${found_tgz}" ]]; then
			tgz_src="${found_tgz}"
			echo "找到 mongosh tgz 文件: ${tgz_src}"
		fi
	fi

	if [[ -z "${tgz_src}" || ! -f "${tgz_src}" ]]; then
		echo "警告: 未找到 mongosh tgz 文件，跳过 mongosh 安装。"
		echo "  要安装 mongosh，请将 mongosh-*.tgz 文件放在 ${SCRIPT_DIR}/"
		echo "  或设置 MONGOSH_TGZ_PATH 环境变量。"
		return 0
	fi

	echo "正在从 ${tgz_src} 安装 mongosh..."
	
	# Extract tgz
	tar -xzf "${tgz_src}" -C "${tmpdir}" || {
		echo "错误: 解压 ${tgz_src} 失败"
		return 1
	}

	# Find mongosh binary in extracted directory
	local mongosh_bin
	mongosh_bin="$(find "${tmpdir}" -name "mongosh" -type f -executable 2>/dev/null | head -n 1)"
	
	if [[ -z "${mongosh_bin}" || ! -f "${mongosh_bin}" ]]; then
		echo "错误: 在解压的归档文件中未找到 mongosh 二进制文件"
		return 1
	fi

	# Copy mongosh to our bin directory
	cp -f "${mongosh_bin}" "${MONGODB_BIN_DIR}/mongosh" || {
		echo "错误: 复制 mongosh 到 ${MONGODB_BIN_DIR} 失败"
		return 1
	}

	# Set permissions (验证用户存在后再设置)
	if id -u "${MONGODB_USER}" >/dev/null 2>&1 && getent group "${MONGODB_GROUP}" >/dev/null 2>&1; then
		chown "${MONGODB_USER}:${MONGODB_GROUP}" "${MONGODB_BIN_DIR}/mongosh" || {
			echo "警告: 设置 mongosh 文件所有者失败，但继续安装"
		}
		chmod 0755 "${MONGODB_BIN_DIR}/mongosh"
	else
		echo "警告: 用户 ${MONGODB_USER} 或组 ${MONGODB_GROUP} 不存在，跳过权限设置"
	fi

	# Create symlink to /usr/local/bin for global access (optional)
	if [[ -d "/usr/local/bin" ]]; then
		ln -sf "${MONGODB_BIN_DIR}/mongosh" "/usr/local/bin/mongosh" || true
		echo "已创建符号链接: /usr/local/bin/mongosh -> ${MONGODB_BIN_DIR}/mongosh"
	fi

	echo "mongosh 安装成功: ${MONGODB_BIN_DIR}/mongosh"
	
	# Verify installation
	if [[ -x "${MONGODB_BIN_DIR}/mongosh" ]]; then
		local version
		version="$("${MONGODB_BIN_DIR}/mongosh" --version 2>/dev/null || echo "unknown")"
		echo "mongosh 版本: ${version}"
	fi
}

write_config() {
	local conf="${MONGODB_CONF_DIR}/mongod.conf"
	local enable_auth="${1:-false}"
	
	if [[ "${enable_auth}" == "true" ]]; then
		cat > "${conf}" <<'EOF'
storage:
  dbPath: /opt/RadMedical/product/tool/mongodb/data
  journal:
    enabled: true
systemLog:
  destination: file
  path: /opt/RadMedical/product/tool/mongodb/logs/mongod.log
  logAppend: true
processManagement:
  fork: false
net:
  bindIp: 0.0.0.0
  port: 27017
security:
  authorization: enabled
setParameter:
  enableLocalhostAuthBypass: false
EOF
	else
		cat > "${conf}" <<'EOF'
storage:
  dbPath: /opt/RadMedical/product/tool/mongodb/data
  journal:
    enabled: true
systemLog:
  destination: file
  path: /opt/RadMedical/product/tool/mongodb/logs/mongod.log
  logAppend: true
processManagement:
  fork: false
net:
  bindIp: 0.0.0.0
  port: 27017
setParameter:
  enableLocalhostAuthBypass: false
EOF
	fi
	# 验证用户存在后再设置权限
	if id -u "${MONGODB_USER}" >/dev/null 2>&1 && getent group "${MONGODB_GROUP}" >/dev/null 2>&1; then
		chown "${MONGODB_USER}:${MONGODB_GROUP}" "${conf}" || {
			echo "警告: 设置配置文件所有者失败，但继续"
		}
	else
		echo "警告: 用户 ${MONGODB_USER} 或组 ${MONGODB_GROUP} 不存在，跳过配置文件权限设置"
	fi
	chmod 0644 "${conf}"
}

write_systemd_unit() {
	# 检测 systemd 版本，判断是否支持资源限制选项
	# MemoryMax 和 AllowedCPUs 需要 systemd 218+ 版本
	local systemd_version="0"
	local use_resource_limits=false
	
	# 尝试多种方式获取 systemd 版本
	if command -v systemd >/dev/null 2>&1; then
		# 方法1: systemd --version 通常输出 "systemd 219" 这样的格式
		systemd_version=$(systemd --version 2>/dev/null | head -n1 | grep -oE '[0-9]+' | head -n1 || echo "0")
	fi
	
	# 如果还是 0，尝试从 systemctl 获取
	if [[ "${systemd_version}" == "0" ]] && command -v systemctl >/dev/null 2>&1; then
		systemd_version=$(systemctl --version 2>/dev/null | head -n1 | grep -oE '[0-9]+' | head -n1 || echo "0")
	fi
	
	# 如果版本号有效且 >= 218，则使用资源限制
	if [[ -n "${systemd_version}" && "${systemd_version}" != "0" && "${systemd_version}" -ge 218 ]]; then
		use_resource_limits=true
		echo "检测到 systemd 版本 ${systemd_version}，支持资源限制选项"
	else
		echo "检测到 systemd 版本较旧（${systemd_version}），将跳过资源限制选项以避免兼容性问题"
	fi
	
	# CPU/Memory constraints:
	# - MemoryMax=20%    -> limit memory usage to 20% of host (需要 systemd 218+)
	# - CPUQuota=20%     -> limit CPU time to 20% total (需要 systemd 213+)
	# - AllowedCPUs=0-1  -> restrict to at most 2 CPU cores (需要 systemd 218+)
	# You may adjust AllowedCPUs if you want different specific cores.
	
	if [[ "${use_resource_limits}" == "true" ]]; then
		cat > "${SYSTEMD_UNIT}" <<'EOF'
[Unit]
Description=MongoDB Database Server
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=mongod
Group=mongod
ExecStart=/usr/bin/mongod --config /opt/RadMedical/product/tool/mongodb/conf/mongod.conf
ExecStartPre=/bin/mkdir -p /opt/RadMedical/product/tool/mongodb/data /opt/RadMedical/product/tool/mongodb/logs
ExecStartPre=/bin/chown -R mongod:mongod /opt/RadMedical/product/tool/mongodb
Restart=on-failure
RestartSec=5s
LimitNOFILE=64000

# Resource controls (requires systemd 218+)
MemoryAccounting=true
CPUAccounting=true
MemoryMax=20%
CPUQuota=20%
AllowedCPUs=0-1
TasksMax=infinity

[Install]
WantedBy=multi-user.target
EOF
	else
		cat > "${SYSTEMD_UNIT}" <<'EOF'
[Unit]
Description=MongoDB Database Server
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=mongod
Group=mongod
ExecStart=/usr/bin/mongod --config /opt/RadMedical/product/tool/mongodb/conf/mongod.conf
ExecStartPre=/bin/mkdir -p /opt/RadMedical/product/tool/mongodb/data /opt/RadMedical/product/tool/mongodb/logs
ExecStartPre=/bin/chown -R mongod:mongod /opt/RadMedical/product/tool/mongodb
Restart=on-failure
RestartSec=5s
LimitNOFILE=64000

# Resource controls are not available in this systemd version
# Note: MemoryMax, CPUQuota, and AllowedCPUs require systemd 218+

[Install]
WantedBy=multi-user.target
EOF
	fi
	chmod 0644 "${SYSTEMD_UNIT}"
}

wait_for_mongodb() {
	local require_auth="${1:-false}"
	local max_attempts=30
	local attempt=0
	echo "等待 MongoDB 就绪..."
	
	local mongo_cmd=""
	if command -v mongosh >/dev/null 2>&1; then
		mongo_cmd="mongosh"
	elif command -v mongo >/dev/null 2>&1; then
		mongo_cmd="mongo"
	else
		echo "警告: 未找到 mongosh 或 mongo 命令，跳过就绪检查。"
		return 0
	fi
	
	while [[ ${attempt} -lt ${max_attempts} ]]; do
		if [[ "${require_auth}" == "true" ]]; then
			# With authentication
			local local_conn="mongodb://${MONGODB_DB_USER}:${MONGODB_DB_PASSWORD}@localhost:${MONGODB_PORT}/${MONGODB_DB_NAME}?authSource=${MONGODB_DB_NAME}&authMechanism=SCRAM-SHA-1"
			if ${mongo_cmd} "${local_conn}" --quiet --eval "db.adminCommand('ping')" >/dev/null 2>&1; then
				echo "MongoDB 已就绪（已启用认证）。"
				return 0
			fi
		else
			# Without authentication
			if ${mongo_cmd} --quiet --eval "db.adminCommand('ping')" >/dev/null 2>&1; then
				echo "MongoDB 已就绪。"
				return 0
			fi
		fi
		sleep 1
		attempt=$((attempt + 1))
	done
	echo "警告: MongoDB 可能尚未完全就绪。"
	return 1
}

init_mongodb_user() {
	echo "正在初始化 MongoDB 用户和数据库..."
	
	local mongo_cmd=""
	if command -v mongosh >/dev/null 2>&1; then
		mongo_cmd="mongosh"
	elif command -v mongo >/dev/null 2>&1; then
		mongo_cmd="mongo"
	else
		echo "错误: 未找到 mongosh 或 mongo 命令，无法初始化用户。"
		return 1
	fi
	
	# Create database and user
	${mongo_cmd} --quiet <<EOF
use ${MONGODB_DB_NAME}
db.createUser({
  user: "${MONGODB_DB_USER}",
  pwd: "${MONGODB_DB_PASSWORD}",
  roles: [
    { role: "readWrite", db: "${MONGODB_DB_NAME}" },
    { role: "dbAdmin", db: "${MONGODB_DB_NAME}" }
  ]
})
EOF
	
	if [[ $? -eq 0 ]]; then
		echo "用户 '${MONGODB_DB_USER}' 在数据库 '${MONGODB_DB_NAME}' 中创建成功。"
		return 0
	else
		echo "警告: 创建用户失败，用户可能已存在。"
		return 1
	fi
}

test_mongodb_connection() {
	echo "正在测试 MongoDB 连接..."
	
	local mongo_cmd=""
	if command -v mongosh >/dev/null 2>&1; then
		mongo_cmd="mongosh"
	elif command -v mongo >/dev/null 2>&1; then
		mongo_cmd="mongo"
	else
		echo "错误: 未找到 mongosh 或 mongo 命令，无法测试连接。"
		return 1
	fi
	
	# Test connection with authentication using localhost (since we're on the same server)
	local local_connection_string="mongodb://${MONGODB_DB_USER}:${MONGODB_DB_PASSWORD}@localhost:${MONGODB_PORT}/${MONGODB_DB_NAME}?authSource=${MONGODB_DB_NAME}&authMechanism=SCRAM-SHA-1"
	
	if ${mongo_cmd} "${local_connection_string}" --quiet --eval "db.adminCommand('ping')" >/dev/null 2>&1; then
		echo "✓ 连接测试成功！"
		echo "连接字符串（供外部使用）: ${MONGODB_CONNECTION_STRING}"
		return 0
	else
		echo "✗ 连接测试失败！"
		echo "请检查 MongoDB 日志并确认已启用认证。"
		return 1
	fi
}

diagnose_mongodb_failure() {
	echo ""
	echo "=========================================="
	echo "MongoDB 启动失败，正在诊断问题..."
	echo "=========================================="
	
	# 检查服务状态
	echo "服务状态："
	systemctl --no-pager status mongod || true
	
	# 检查日志文件
	local log_file="${MONGODB_LOG_DIR}/mongod.log"
	if [[ -f "${log_file}" ]]; then
		echo ""
		echo "最近的错误日志（最后 30 行）："
		echo "----------------------------------------"
		tail -n 30 "${log_file}" || true
		echo "----------------------------------------"
	else
		echo ""
		echo "警告: 日志文件 ${log_file} 不存在"
	fi
	
	# 检查 journalctl 日志
	echo ""
	echo "systemd 日志（最后 20 行）："
	echo "----------------------------------------"
	journalctl -u mongod -n 20 --no-pager || true
	echo "----------------------------------------"
	
	# 检查常见问题
	echo ""
	echo "常见问题检查："
	
	# 检查数据目录权限
	if [[ -d "${MONGODB_DATA_DIR}" ]]; then
		local data_owner=$(stat -c '%U:%G' "${MONGODB_DATA_DIR}" 2>/dev/null || echo "unknown")
		echo "  数据目录所有者: ${data_owner} (应该是 ${MONGODB_USER}:${MONGODB_GROUP})"
		if [[ "${data_owner}" != "${MONGODB_USER}:${MONGODB_GROUP}" ]]; then
			echo "  ⚠ 数据目录所有者不正确，尝试修复..."
			chown -R "${MONGODB_USER}:${MONGODB_GROUP}" "${MONGODB_DATA_DIR}" 2>/dev/null || true
		fi
	fi
	
	# 检查日志目录权限
	if [[ -d "${MONGODB_LOG_DIR}" ]]; then
		local log_owner=$(stat -c '%U:%G' "${MONGODB_LOG_DIR}" 2>/dev/null || echo "unknown")
		echo "  日志目录所有者: ${log_owner} (应该是 ${MONGODB_USER}:${MONGODB_GROUP})"
		if [[ "${log_owner}" != "${MONGODB_USER}:${MONGODB_GROUP}" ]]; then
			echo "  ⚠ 日志目录所有者不正确，尝试修复..."
			chown -R "${MONGODB_USER}:${MONGODB_GROUP}" "${MONGODB_LOG_DIR}" 2>/dev/null || true
		fi
	fi
	
	# 检查配置文件
	local conf_file="${MONGODB_CONF_DIR}/mongod.conf"
	if [[ -f "${conf_file}" ]]; then
		echo "  配置文件存在: ${conf_file}"
		# 检查配置文件语法
		if /usr/bin/mongod --config "${conf_file}" --test 2>&1 | grep -q "error"; then
			echo "  ⚠ 配置文件可能有语法错误"
		fi
	else
		echo "  ⚠ 配置文件不存在: ${conf_file}"
	fi
	
	# 检查端口占用
	if command -v netstat >/dev/null 2>&1; then
		if netstat -tuln | grep -q ":${MONGODB_PORT} "; then
			echo "  ⚠ 端口 ${MONGODB_PORT} 已被占用"
		fi
	elif command -v ss >/dev/null 2>&1; then
		if ss -tuln | grep -q ":${MONGODB_PORT} "; then
			echo "  ⚠ 端口 ${MONGODB_PORT} 已被占用"
		fi
	fi
	
	echo "=========================================="
	echo ""
}

enable_and_start() {
	systemctl daemon-reload
	systemctl enable mongod
	systemctl restart mongod
	sleep 3
	
	# 检查服务是否成功启动
	if ! systemctl is-active --quiet mongod; then
		diagnose_mongodb_failure
		return 1
	fi
	
	systemctl --no-pager --full status mongod || true
	return 0
}

configure_firewalld_port() {
	if ! command -v firewall-cmd >/dev/null 2>&1; then
		echo "firewall-cmd 未安装，跳过 firewalld 端口放行。"
		return
	 fi

	if systemctl is-active --quiet firewalld; then
		if firewall-cmd --list-ports | grep -qw "${MONGODB_PORT}/tcp"; then
			echo "firewalld 已放行端口 ${MONGODB_PORT}/tcp，跳过配置。"
		else
			echo "配置 firewalld 放行端口 ${MONGODB_PORT}/tcp..."
			firewall-cmd --permanent --add-port=${MONGODB_PORT}/tcp
			firewall-cmd --reload
		fi
	else
		echo "firewalld 未运行，跳过端口放行步骤。"
	fi
}

main() {
	ensure_root
	create_user_group
	prepare_dirs
	install_from_rpm
	install_mongosh
	
	# Step 1: Write config without authentication (for initial user creation)
	write_config "false"
	write_systemd_unit
	# Make sure vendor unit doesn't conflict with our overrides
	systemctl disable mongod >/dev/null 2>&1 || true
	
	# Step 2: Start MongoDB without authentication
	if ! enable_and_start; then
		echo ""
		echo "错误: MongoDB 服务启动失败，请根据上述诊断信息解决问题后重试。"
		echo "常见解决方法："
		echo "1. 检查日志文件: ${MONGODB_LOG_DIR}/mongod.log"
		echo "2. 检查目录权限: chown -R ${MONGODB_USER}:${MONGODB_GROUP} ${MONGODB_BASE_DIR}"
		echo "3. 检查配置文件: ${MONGODB_CONF_DIR}/mongod.conf"
		echo "4. 手动测试启动: /usr/bin/mongod --config ${MONGODB_CONF_DIR}/mongod.conf"
		exit 1
	fi
	wait_for_mongodb
	
	# Step 3: Initialize user and database
	init_mongodb_user
	
	# Step 4: Enable authentication and restart
	echo "正在启用认证..."
	write_config "true"
	systemctl restart mongod
	sleep 3
	if ! systemctl is-active --quiet mongod; then
		diagnose_mongodb_failure
		echo "错误: 启用认证后 MongoDB 服务启动失败"
		exit 1
	fi
	wait_for_mongodb "true"

	# Step 4.5: Configure firewalld port
	configure_firewalld_port
	
	# Step 5: Test connection
	test_mongodb_connection
	
	echo ""
	echo "=========================================="
	echo "MongoDB 安装完成！"
	echo "=========================================="
	echo "安装路径: ${MONGODB_BASE_DIR}"
	echo "服务: mongod (已启用开机自启)"
	echo "资源限制: 如果 systemd 版本 >= 218，则启用 MemoryMax=20%, CPUQuota=20%, AllowedCPUs=0-1"
	echo "          否则资源限制将不会生效（不影响 MongoDB 运行）"
	echo ""
	echo "连接字符串:"
	echo "${MONGODB_CONNECTION_STRING}"
	echo ""
	echo "使用 mongosh 连接:"
	echo "  mongosh \"${MONGODB_CONNECTION_STRING}\""
	echo ""
	echo "使用 mongo 连接:"
	echo "  mongo \"${MONGODB_CONNECTION_STRING}\""
	echo "=========================================="
}

main "$@"




